package com.api.gbhg.liuwenbo.action;

import com.api.gbhg.liuwenbo.dao.ProjectDetailsUtil;
import com.api.gbhg.liwenjun.VersionFlowUtil;
import com.google.common.base.Joiner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.general.BaseBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

/**
 * 金额校验扣减Action
 */
public class AmountVerification implements Action {

//    private final Logger logger = LoggerFactory.getLogger(AmountVerification.class);
    private static final Logger logger = LoggerFactory.getLogger("gbhg");

    private static int thisYear = LocalDate.now().getYear();
    private static int lastYear = LocalDate.now().getYear() - 1;
    private static String YJ ;
    private static String XJ ;
    private static String TSDW ;


    static{
        try {
            Properties prop=new Properties();
            prop.load(new InputStreamReader(AmountVerification.class.getResourceAsStream("../conf/Verification.properties")));
            //YJ = prop.getProperty("yj");
            //XJ = prop.getProperty("xj");
            //TSDW = prop.getProperty("tsdw");
            YJ = new BaseBean().getPropValue("Verification","yj");
            XJ = new BaseBean().getPropValue("Verification","xj");
            TSDW = new BaseBean().getPropValue("Verification","tsdw");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String execute(RequestInfo requestInfo) {
        int mainTableId = VersionFlowUtil.getFlowTableLableId(requestInfo.getWorkflowid());//获取formid 例如：-83
        String mainTabName = getMainTableName(mainTableId);//获取主表名
        Integer dw = getwofkflowDw(mainTabName, requestInfo.getRequestid());

        RecordSet dwSet = new RecordSet();
        dwSet.executeQuery("select case when exists  (select dlhsdw from uf_dlhsdwgl where dlhsdw=" + dw + ") then  (select dlhsdw from uf_dlhsdwgl where dlhsdw=" + dw + ")  else (select supsubcomid from hrmsubcompany where id=" + dw + ") end id");
        dwSet.next();
        //获取单位Id
//        dw = dwSet.getInt("id"); //up 4-15
        logger.info("单位" + dw);
        List<String> flowDetailTableNames = getDetailTables(mainTableId);//获取明细表名称

        String flowTableName = VersionFlowUtil.getFlowTableName(requestInfo.getWorkflowid());//获取表名

        String id = getIdByTable(flowTableName, requestInfo.getRequestid()); //获取流程当前id

        Map<String, Object> dnData = getDataBydt(flowDetailTableNames.get(0), id,"dfczbkxmdnys");
        Map<String, Object> snData = getDataBydt(flowDetailTableNames.get(1), id,"dfczbkxmsnjz");
        Property[] properties = requestInfo.getMainTableInfo().getProperty();
        Map<String,String> mainTable = new HashMap<>();
        for(Property property : properties){
            mainTable.put(property.getName(), property.getValue());
        }

        Integer ysnd = Integer.parseInt(mainTable.get("ysnd"));

        Map<String, Object> msgMap1 = MoneyVc2(dnData,ysnd,dw,ysnd,"dn");//0,10_1:100
        Map<String, Object> msgMap2 = MoneyVc2(snData, ysnd - 1,dw,ysnd,"sn");


        if (msgMap1.get("code").toString().equals("200") && msgMap2.get("code").toString().equals("200")){
            return SUCCESS;
        }else{
            Map<String, Object> map = new HashMap<>();
            map.putAll(msgMap1);
            map.putAll(msgMap2);
            map.remove("code");
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                sb.append(entry.getKey() + " | ");
            }
            requestInfo.getRequestManager().setMessagecontent(sb.toString());
            requestInfo.getRequestManager().setMessageid("1");
            return FAILURE_AND_CONTINUE;
        }

       /* RecordSetTrans rst = new RecordSetTrans();
        rst.setAutoCommit(false);
        boolean s1 = false;
        boolean s2 = false;
        boolean sql1 = false;
        boolean sql2 = false;
        boolean sql3 = false;

        if (msgMap1.get("msg").toString().equals("SUCCESS") && msgMap2.get("msg").toString().equals("SUCCESS")){ //判断校验是否通过

            StringBuffer fzydnzc = new StringBuffer();//非中央当年支出
            StringBuffer fzysnzc = new StringBuffer();//非中央上年支出
            StringBuffer zydnzckm = new StringBuffer();//中央当年支出科目
            StringBuffer zydnzcxj = new StringBuffer();//中央当年支出下级
            StringBuffer zysnzckm = new StringBuffer();//中央上年支出科目
            StringBuffer zysnzcxj = new StringBuffer();//中央上年支出下级

            Map<String,Object> snXjMap = new HashMap<>();
            Map<String,Object> dnXjMap = new HashMap<>();

            //记录id 用作为sql条件
            List<String> fzyConditionId = new ArrayList<>();
            List<String> zyConditionIdKm = new ArrayList<>();
            List<String> zyConditionIdXj = new ArrayList<>();
            //0,10_1:100
            if (!snData.isEmpty()){ //判断上年数据是否存在
                for (Map.Entry<String, Object> entry : snData.entrySet()) {
                    String[] srly = entry.getKey().split(",");
                    if (srly[0].equals("0")) { //判断是否为中央
                        String[] srid = srly[1].split(":")[0].split("_");
                        if (srid[0].equals("9")){ //科目级
                            zysnzckm.append(" when id = " + srid[1] + " then yqndsjjzje - " + entry.getValue() + " ");
                            zyConditionIdKm.add(srid[1]);
                        }else if (srid[0].equals("10")){ //下级
                            zysnzcxj.append(" when id = " + srid[1] + " then yqndsjjzje - " + entry.getValue() + " ");
                            zyConditionIdXj.add(srid[1]);
                            snXjMap.put(srid[1],entry.getValue());
                        }
                    }else{ //非中央
                        String fzyflId = srly[1].split(":")[0];
                        String fzyId = VerificationDBUtil.getFzyIdByFlid(dw, fzyflId);
                        fzysnzc.append(" when id = " + fzyId + " then yqndsjjzje - " + entry.getValue() + " ");
                        fzyConditionId.add(fzyId);
                    }
                }
            }else{
                s1 = true;
            }

            if (!dnData.isEmpty()){ //判断本年数据是否存在
                for (Map.Entry<String, Object> entry : dnData.entrySet()) {//0,1:100
                    String[] srly = entry.getKey().split(",");
                    if (srly[0].equals("0")) { //判断是否为中央
                        String[] srid = srly[1].split(":")[0].split("_");
                        if (srid[0].equals("9")){ //科目级
                            zydnzckm.append(" when id = " + srid[1] + " then yjsr - " + entry.getValue() + " ");
                            zyConditionIdKm.add(srid[1]);
                        }else if (srid[0].equals("10")){ //下级
                            zydnzcxj.append(" when id = " + srid[1] + " then yjsr - " + entry.getValue() + " ");
                            zyConditionIdXj.add(srid[1]);
                            dnXjMap.put(srid[1],entry.getValue());
                        }
                    }else{ //非中央
                        String fzyflId = srly[1].split(":")[0];
                        String fzyId = VerificationDBUtil.getFzyIdByFlid(dw, fzyflId);
                        fzydnzc.append(" when id = " + fzyId + " then yjsr - " + entry.getValue() + " ");
                        fzyConditionId.add(fzyId);
                    }
                }
            }else{
                s2 = true;
            }

            try {
                String zyKmSql = VerificationDBUtil.setupKm(zydnzckm, zysnzckm, zyConditionIdKm);
                if (!zyKmSql.isEmpty()){
                    sql1 = rst.executeUpdate(zyKmSql);
                }else{
                    sql1 = true;
                }
                String zyXjSql = VerificationDBUtil.setupXj(zydnzcxj, zysnzcxj, zyConditionIdXj);
                if (!zyXjSql.isEmpty()){

                    if (snXjMap.isEmpty())
                        sql2 = true;

                    for (Map.Entry<String,Object> entry:snXjMap.entrySet()) {  //扣减上年
                        List<String> superiorId = TreeStuctureDBUtil.getSuperiorId(Integer.valueOf(entry.getKey()));
                        String joinId = Joiner.on(",").join((Iterable<?>) superiorId);
                        String sql = VerificationDBUtil.joinXjSql(joinId, entry.getValue().toString(), "yqndsjjzje");
                        sql2 = rst.executeUpdate(sql);  //扣减下级金额，同时扣减所有上级金额
                        if (!sql2){
                            break;
                        }
                        if (sql2){
                            String kmsql = VerificationDBUtil.joinKmsql(entry.getKey(), "yqndsjjzje", entry.getValue().toString());
                            sql2 = rst.executeUpdate(kmsql);//扣减科目金额
                            if (!sql2){
                                break;
                            }
                        }
                    }

                    if (sql2){
                        for (Map.Entry<String,Object> entry:dnXjMap.entrySet()) {  //扣减本年
                            List<String> superiorId = TreeStuctureDBUtil.getSuperiorId(Integer.valueOf(entry.getKey()));
                            String joinId = Joiner.on(",").join((Iterable<?>) superiorId);
                            String sql = VerificationDBUtil.joinXjSql(joinId, entry.getValue().toString(), "yjsr");
                            sql2 = rst.executeUpdate(sql); //扣减下级金额，同时扣减所有上级金额
                            if (!sql2){
                                break;
                            }
                            if (sql2){
                                String kmsql = VerificationDBUtil.joinKmsql(entry.getKey(), "yjsr", entry.getValue().toString());
                                sql2 = rst.executeUpdate(kmsql);//扣减科目金额
                                if (!sql2){
                                    break;
                                }
                            }
                        }
                    }
//                    sql2 = rst.executeUpdate(zyXjSql);
                }else{
                    sql2 = true;
                }

                String fzySql = VerificationDBUtil.setupFzy(fzydnzc, fzysnzc, fzyConditionId);
                if (!fzySql.isEmpty()){
                    sql3 = rst.executeUpdate(fzySql);
                }else{
                    sql3 = true;
                }
            } catch (Exception e) {
                e.printStackTrace();
                rst.rollback();
            }
        }
        if (sql1 && sql2 && sql3){
            rst.commit();
            return SUCCESS;
        }else{
            rst.rollback();
            Map<String, Object> map = new HashMap<>();
            map.putAll(msgMap1);
            map.putAll(msgMap2);
            map.remove("msg");
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                sb.append(entry.getKey() + " | ");
            }
            requestInfo.getRequestManager().setMessagecontent(sb.toString());
            requestInfo.getRequestManager().setMessageid("1");
            return FAILURE_AND_CONTINUE;
        }*/



        /*StringBuilder kmDn = new StringBuilder();//一级本年
        StringBuilder kmSn = new StringBuilder();//一级上年
        StringBuilder xjDn = new StringBuilder();//下级本年
        StringBuilder xjSn = new StringBuilder();//下级上年
        StringBuilder dfczDn = new StringBuilder();//地方财政本年
        StringBuilder dfczSn = new StringBuilder();//地方财政上年
        StringBuilder fzyDn = new StringBuilder();//非中央本年
        StringBuilder fzySn = new StringBuilder();//费中央上年
        boolean s1 = false;
        boolean s2 = false;
        boolean s3 = false;
        boolean s4 = false;
        boolean s5 = false;
        boolean s6 = false;
        try {
            if (msgMap1.get("msg").toString().equals("SUCCESS") && msgMap2.get("msg").toString().equals("SUCCESS")) {

                List<String> dfIdList = new ArrayList<>();
                List<String> fzyIdList = new ArrayList<>();
                List<String> kmIdList = new ArrayList<>();
                List<String> xjIdList = new ArrayList<>();
                StringBuilder dfdnzc = new StringBuilder();//地方当年支出
                StringBuilder dfsnzc = new StringBuilder();//地方上年支出
                StringBuilder fzydnzc = new StringBuilder();//非中央当年支出
                StringBuilder fzysnzc = new StringBuilder();//非中央上年支出
                StringBuilder kmdnzc = new StringBuilder();//一级本年支出
                StringBuilder kmsnzc = new StringBuilder();//一级上年支出
                StringBuilder xjdnzc = new StringBuilder();//下级本年支出
                StringBuilder xjsnzc = new StringBuilder();//下级上年支出

                if (!dnData.isEmpty()) {
                    for (Map.Entry<String, Object> entry : dnData.entrySet()) {
                        String[] split = entry.getKey().split(",");
                        if (split[0].equals("7")) { //地方财政
//                            if (syje1.toString().isEmpty()&&dfczSb1.toString().isEmpty()){
//                                dfczSb1.append(" update uf_dfczbkxm set sywy = (case ");
//                                syje1.append(" sjzcwy = (case ");
//                            }

                            dfczDn.append(" when id = " + split[1] + " then yjsrsy - " + entry.getValue() + " ");
                            dfdnzc.append(" when id = " + split[1] + " then  sjzc+" + entry.getValue() + " ");
                            dfIdList.add(split[1]);

                        } else if (split[0].equals("1")) { //中央财政
                            String[] xmid = split[1].split("_");// 9_1,10_2   9 属于一级 10 属于二级 后面则是id
                            if (xmid[0].equals(YJ) || xmid[0].equals("27")) { //一级
                                kmDn.append(" when id = " + xmid[1] + " then yjsrsy - " + entry.getValue() + " ");
                                kmdnzc.append(" when id = " + xmid[1] + " then  yhpje+" + entry.getValue() + "  ");
                                kmIdList.add(xmid[1]);
                            } else {
                                xjDn.append(" when id = " + xmid[1] + " then yjsrsy - " + entry.getValue() + " ");
                                xjdnzc.append(" when id = " + xmid[1] + " then  yhpje+" + entry.getValue() + "  ");
                                xjIdList.add(xmid[1]);

                                List<String> superiorId = TreeStuctureDBUtil.getSuperiorId(Integer.valueOf(xmid[1])); //获取所有上级
                                superiorId.remove(xmid[1]);//删除自己本身得id
                                String sql1 = " update uf_zyczbksr_Xj set yjsrsy = yjsrsy -"+entry.getValue()+" , yhpje = yhpje + "+entry.getValue()+" where id in ("+Joiner.on(",").join((Iterable<?>) superiorId)+")  ";
                                boolean kjXj = rst.executeUpdate(sql1); //扣减下级表

                                String kmid = VerificationDBUtil.getKmIdByXjId(xmid[1]);
                                String sql2 = " update uf_zyczbksr_km set yjsrsy = yjsrsy - "+entry.getValue()+",yhpje = yhpje + "+entry.getValue()+" where id = "+kmid+" ";
                                boolean kjKm = rst.executeUpdate(sql2); //扣减科目表
                                if (kjXj&&kjKm){
                                    s5 = true;
                                }else{
                                    msgMap1.put("扣减失败！","tips");
                                    s5 = false;
                                    break;
                                }
                            }
                        } else { //非中央
                            fzyDn.append(" when srly = " + split[0] + " and srnf = " + thisYear + " and srdw = " + dw + " then yjsrsy - " + entry.getValue() + " ");
                            fzydnzc.append(" when srly = " + split[0] + " and srnf = " + thisYear + " and srdw = " + dw + " then  sjzc+" + entry.getValue() + " ");
                            fzyIdList.add(split[0]);
                        }
                    }
                } else {
                    s1 = true;
                }


                if (!snData.isEmpty()) {
                    for (Map.Entry<String, Object> entry : snData.entrySet()) {
                        String[] split = entry.getKey().split(",");//上年
                        if (split[0].equals("7")) { //地方财政
                            dfczSn.append(" when id = " + split[1] + " then jzsyje - " + entry.getValue() + " ");
                            dfsnzc.append(" when id = " + split[1] + " then  jzyyje+" + entry.getValue() + " ");
                            dfIdList.add(split[1]);
                        } else if (split[0].equals("1")) {
                            String[] xmid = split[1].split("_");// 9_1,10_2   9 属于一级 10 属于二级 后面则是id
                            if (xmid[0].equals(YJ) || xmid[0].equals("27")) { //一级
                                kmSn.append(" when id = " + xmid[1] + " then jzsyje - " + entry.getValue() + " ");
                                kmsnzc.append(" when id = " + xmid[1] + " then  jzyyje+" + entry.getValue() + "  ");
                                kmIdList.add(xmid[1]);
                            } else { //二级
                                xjSn.append(" when id = " + xmid[1] + " then jzsyje - " + entry.getValue() + " ");
                                xjsnzc.append(" when id = " + xmid[1] + " then  jzyyje+" + entry.getValue() + "  ");
                                xjIdList.add(xmid[1]);


                                List<String> superiorId = TreeStuctureDBUtil.getSuperiorId(Integer.valueOf(xmid[1])); //获取所有上级
                                superiorId.remove(xmid[1]);//删除自己本身得id
                                String sql1 = " update uf_zyczbksr_Xj set jzsyje = jzsyje -"+entry.getValue()+" , jzyyje = jzyyje + "+entry.getValue()+" where id in ("+Joiner.on(",").join((Iterable<?>) superiorId)+")  ";
                                boolean kjXj = rst.executeUpdate(sql1); //扣减下级表

                                String kmid = VerificationDBUtil.getKmIdByXjId(xmid[1]);
                                String sql2 = " update uf_zyczbksr_km set jzsyje = jzsyje - "+entry.getValue()+",jzyyje = jzyyje + "+entry.getValue()+" where id = "+kmid+" ";
                                boolean kjKm = rst.executeUpdate(sql2); //扣减科目表
                                if (kjXj&&kjXj){
                                    s6 = true;
                                }else{
                                    msgMap1.put("扣减失败！","tips");
                                    s6 = false;
                                    break;
                                }
                            }
                        } else { //非中央
                            fzySn.append(" when srly = " + split[0] + " and srnf = " + lastYear + " and srdw = " + dw + " then jzsyje - " + entry.getValue() + " ");
                            fzysnzc.append(" when srly = " + split[0] + " and srnf = " + lastYear + " and srdw = " + dw + " then  jzyyje+" + entry.getValue() + " ");
                            fzyIdList.add(split[0]);
                        }
                    }
                } else {
                    s2 = true;
                }

                //---------------------------------------------------------------------------------------------------------//拼接sql

                String dfSql = VerificationDBUtil.setdfSql(dfczDn, dfczSn, dfdnzc, dfsnzc, dfIdList); //地方sql
                if (!dfSql.isEmpty()) {
                    s1 = rst.executeUpdate(dfSql);
                } else {
                    s1 = true;
                }


                String fzySql = VerificationDBUtil.setfzySql(fzyDn, fzySn, fzydnzc, fzysnzc, fzyIdList);//第三类 sql
                if (!fzySql.isEmpty()) {
                    s2 = rst.executeUpdate(fzySql);
                } else {
                    s2 = true;
                }

                String kmSql = VerificationDBUtil.setkmSql(kmDn, kmSn, kmdnzc, kmsnzc, kmIdList); //中央 一级
                if (!kmSql.isEmpty()) {
                    s3 = rst.executeUpdate(kmSql);
                } else {
                    s3 = true;
                }

                String xjSql = VerificationDBUtil.setxjSql(xjDn, xjSn, xjdnzc, xjsnzc, xjIdList); //中央 下级
                if (!xjSql.isEmpty()) {
                    s4 = rst.executeUpdate(xjSql);
                } else {
                    s4 = true;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            rst.rollback();
        }*/

        /*if (s1 && s2 && s3 && s4 && s5) {
            rst.commit();
            return SUCCESS;
        } else {
            rst.rollback();
            Map<String, Object> map = new HashMap<>();
            map.putAll(msgMap1);
            map.putAll(msgMap2);
            map.remove("msg");
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                sb.append(entry.getKey() + " | ");
            }
            requestInfo.getRequestManager().setMessagecontent(sb.toString());
            requestInfo.getRequestManager().setMessageid("1");
            return FAILURE_AND_CONTINUE;
        }*/
    }


    public static String getMainTableName(Integer mainTableId) {
        RecordSet rs = new RecordSet();
        String sql = " select tablename from workflow_bill where id = " + mainTableId + " ";
        rs.executeQuery(sql);
        rs.next();
        return rs.getString("tablename");
    }

    public static Integer getwofkflowDw(String tabName, String requestid) {
        RecordSet rs = new RecordSet();
        String sql = " select * from " + tabName + " where requestId = " + requestid + "  ";
        rs.executeQuery(sql);
        rs.next();
//        Integer sbdw = rs.getInt("sbdw");
//        if (sbdw == null) {
//            return rs.getInt("sqdw");
//        } else {
//            return sbdw;
//        }
        return rs.getInt("szdlhsdw");
    }

    public static Map<String, Object> MoneyVc(Map<String, Object> data, int nf, Integer dw) {
        boolean IsSuccess = true;
        Map<String, Object> msgMap = new HashMap<>();
        if (data.isEmpty()) {
            msgMap.put("msg", "SUCCESS");
            return msgMap;
        }

//        if (nf == LocalDate.now().getYear()) {
//            je = "yjsr";
//        } else {
//            je = "yqndsjjzje";
//        }

        RecordSet dfcz = getDfczbkxm(nf); //地方财政
        Map<String, Object> dfczMap = new HashMap<>();
        Map<String, Object> dfczMapName = new HashMap<>();
        while (dfcz.next()) {
            dfczMap.put(dfcz.getString("id"), dfcz.getDouble("je"));
            dfczMapName.put(dfcz.getString("id"), dfcz.getString("xmmc"));
        }

        RecordSet fzy = getfzyczbkjcsj(nf, dw); //非中央
        Map<String, Object> fzyMap = new HashMap<>();
        while (fzy.next()) {
            fzyMap.put(fzy.getString("srly"), fzy.getDouble("je"));
        }

        List<String> kmtbId = new ArrayList<>();
        RecordSet zy_km = getZyczbksr_km(nf); //一级
        Map<String, Object> kmMap = new HashMap<>();
        Map<String, Object> kmMapName = new HashMap<>();
        while (zy_km.next()) {
            if (zy_km.getDouble("srsy") == 0 && zy_km.getDouble("yhpje") == 0) {
                kmMap.put(zy_km.getString("id"), zy_km.getDouble("srje"));
                kmtbId.add(zy_km.getString("id"));
            } else {
                kmMap.put(zy_km.getString("id"), zy_km.getDouble("srsy"));
            }
            kmMapName.put(zy_km.getString("id"), zy_km.getString("gnkmmc"));
        }
        if (!kmtbId.isEmpty()) {
            setSynchronizeKM(Joiner.on(",").join((Iterable<?>) kmtbId), nf);
        }

        List<String> xjtbId = new ArrayList<>();
        RecordSet zy_xj = getZyczbksr_Xj(nf);//下级
        Map<String, Object> xjMap = new HashMap<>();
        Map<String, Object> xjMapName = new HashMap<>();
        while (zy_xj.next()) {
            if (zy_xj.getDouble("srsy") == 0 ) {
                xjMap.put(zy_xj.getString("id"), zy_xj.getDouble("srje"));
                xjtbId.add(zy_xj.getString("id"));
            } else {
                xjMap.put(zy_xj.getString("id"), zy_xj.getDouble("srsy"));
            }
            xjMapName.put(zy_xj.getString("id"), zy_xj.getString("srzx"));
        }
        if (!xjtbId.isEmpty()) {
            setSynchronizeXJ(Joiner.on(",").join((Iterable<?>) xjtbId), nf);
        }


        for (Map.Entry<String, Object> entry : data.entrySet()) {// {'1,6':'20.00',...} 1:预算来源，6:项目id 20.00：金额
            String[] split = entry.getKey().split(",");
            if (split[0].equals("7")) { //判断是否为地方政府财政
                String o = dfczMap.get(split[1]).toString();
                if (Double.valueOf(o) - Double.valueOf(entry.getValue().toString()) < 0) {
                    msgMap.put(dfczMapName.get(split[1]).toString() + "金额不足！", Double.valueOf(entry.getValue().toString()));
                    IsSuccess = false;
                }
            } else if (split[0].equals("1")) { //判断是否属于中央
                String[] xmid = split[1].split("_");// 9_1,10_2   9 属于一级 10 属于二级 后面则是id
                if (xmid[0].equals(YJ) || xmid[0].equals("27")) { //一级
                    if (!kmMap.isEmpty()) {

                        String je = kmMap.get(xmid[1]).toString();
                        if (Double.valueOf(je) - Double.valueOf(entry.getValue().toString()) < 0) {
                            msgMap.put(kmMapName.get(xmid[1]).toString() + "金额不足！", Double.valueOf(entry.getValue().toString()));
                            IsSuccess = false;
                        }
                    } else {
                        msgMap.put("中央财政数据不存在！", "tips");
                        IsSuccess = false;
                    }
                } else { //下级
                    if (!xjMap.isEmpty()) {
                        String je = xjMap.get(xmid[1]).toString();
                        if (Double.valueOf(je) - Double.valueOf(entry.getValue().toString()) < 0) {
                            msgMap.put(xjMapName.get(xmid[1]).toString() + "金额不足！", Double.valueOf(entry.getValue().toString()));
                            IsSuccess = false;
                        }
                    } else {
                        msgMap.put("中央财政数据不存在！", "tips");
                        IsSuccess = false;
                    }

                }
            } else { //非中央
                String name = ProjectDetailsUtil.getBudgetSources(Integer.valueOf(split[0]));
                if (!fzyMap.isEmpty()) { //没有数据
                    if (fzyMap.containsKey(split[0])) { //判断类型是否存在
                        String s = fzyMap.get(split[0]).toString();
                        if (Double.valueOf(s) - Double.valueOf(entry.getValue().toString()) < 0) { //金额比较
                            msgMap.put(name + "金额不足！", Double.valueOf(entry.getValue().toString()));
                            IsSuccess = false;
                        }
                    } else {
                        msgMap.put(name + "不存在！", "tips");
                        IsSuccess = false;
                    }
                } else {
                    msgMap.put(name + "不存在！", "tips");
                    IsSuccess = false;
                }
            }
        }
        if (IsSuccess)
            msgMap.put("msg", "SUCCESS");
        else
            msgMap.put("msg", "FAILURE");
        return msgMap;
    }

    /**
     * 校验核批余额
     * @param data
     * @param nf 预算年份
     * @param dw 单位
     * @param ysnd 预算年份
     * @param type 当年或上年
     * @return
     */
    public static Map<String, Object> MoneyVc2(Map<String, Object> data, int nf,Integer dw,int ysnd,String type) {
        boolean IsSuccess = true;
        Map<String, Object> msgMap = new HashMap<>();
        if (data.isEmpty()) {
            msgMap.put("code", "200");
            return msgMap;
        }
        int jeIndex = 0;
        String msgStr ;
        if (type.equals("dn")) {
//            je = "yjsr";
            jeIndex = 0;
            msgStr = "当年结转核批";
        } else {
//            je = "yqndsjjzje";
            jeIndex = 1;
            msgStr = "上年结转核批";
        }
        RecordSet zycz_km = getZycz_KM(ysnd,dw); //查询所有科目信息
        Map<String,Object> kmMap = new HashMap<>();//数据Map
        Map<String,Object> kmNameMap = new HashMap<>();//名称map (返回信息用到)
        while (zycz_km.next()){
            kmMap.put(zycz_km.getString("id"),zycz_km.getString("yjsrsy")+","+zycz_km.getString("yqndyjjzsyje"));
            kmNameMap.put(zycz_km.getString("id"),zycz_km.getString("gnkmmc"));
        }

        RecordSet zycz_xj = getZycz_XJ(ysnd,dw); //查询所有下级信息
        Map<String,Object> xjMap = new HashMap<>(); //数据Map
        Map<String,Object> xjNameMap = new HashMap<>(); //名称map(返回信息用到)
        while (zycz_xj.next()){
            xjMap.put(zycz_xj.getString("id"),zycz_xj.getString("yjsrsy")+","+zycz_xj.getString("yqndyjjzsyje"));
            xjNameMap.put(zycz_xj.getString("id"),zycz_xj.getString("srzx"));
        }

        RecordSet fzycz = getFzycz(dw,ysnd);//根据dw获取非中央组织架构信息
        Map<String,Object> fzyczMap = new HashMap<>(); //数据Map
        while (fzycz.next()){
            fzyczMap.put(fzycz.getString("flid"),fzycz.getString("yjsrsy")+","+fzycz.getString("yqndyjjzsyje"));
        }

        RecordSet fzyczxm = getFzyczxm(dw,ysnd);//根据dw获取非中央组织架构项目信息
        Map<String,Object> fzyczxmMap = new HashMap<>(); //数据Map
        while (fzyczxm.next()){
            fzyczxmMap.put(fzyczxm.getString("xmid"),fzyczxm.getString("yjsrsy")+","+fzyczxm.getString("yqndyjjzsyje"));
        }

        for (Map.Entry<String, Object> entry : data.entrySet()) {// 0,10_1:100
            String[] srlx = entry.getKey().split(",");  // [0, 10_1:100]
            if (srlx[0].equals("0")) {  //中央
                String[] srid = srlx[1].split(":")[0].split("_"); //[0,10]
                if (srid[0].equals(TSDW)){
                    msgMap.put("中央财政收入不能直接选择单位！", "300");
                    msgMap.put("code","300");
                    return msgMap;
                }
                if (srid[0].equals(YJ)){ //科目级
                    if (kmMap.size()>0){

                        BigDecimal srje = new BigDecimal(kmMap.get(srid[1]).toString().split(",")[jeIndex]);
                        BigDecimal jeV = new BigDecimal(entry.getValue().toString());
                        String newje = srje.subtract(jeV).toString();
                        if (Double.valueOf(newje) < 0 ){
                            msgMap.put(msgStr+"-中央财政收入-["+kmNameMap.get(srid[1]) + "]金额不足！", Double.valueOf(entry.getValue().toString()));
                            IsSuccess = false;
                        }
                    }else{
                        msgMap.put(msgStr+"-中央财政收入数据不存在！", "tips");
                        IsSuccess = false;
                    }
                }else{ //下级
                    if (xjMap.size()>0){
                        BigDecimal srje = new BigDecimal(xjMap.get(srid[1]).toString().split(",")[jeIndex]);
                        BigDecimal jeV = new BigDecimal(entry.getValue().toString());
                        String newje = srje.subtract(jeV).toString();
                        if (Double.valueOf(newje) < 0 ){
                            msgMap.put(msgStr+"-中央财政下级数据-["+xjNameMap.get(srid[1]) + "]金额不足！", Double.valueOf(entry.getValue().toString()));
                            IsSuccess = false;
                        }
                    }else{
                        msgMap.put(msgStr+"-中央财政下级收入数据不存在！", "tips");
                        IsSuccess = false;
                    }
                }
            }else{ //非中央
                String[] srids = srlx[1].split(":")[0].split("_");
                if (srids[0].equals(TSDW)){
                    msgMap.put("非中央财政收入不能直接选择单位！", "300");
                    msgMap.put("code","300");
                    return msgMap;
                }
                if (srids.length==1){//类别
                    if (fzyczMap.size()>0){
                        String srid = srlx[1].split(":")[0].split("_")[0];// 1,9_:100
                        if (fzyczMap.containsKey(srid)){
                            BigDecimal srje = new BigDecimal(fzyczMap.get(srid).toString().split(",")[jeIndex]);
                            BigDecimal jeV = new BigDecimal(entry.getValue().toString());
                            String newje = srje.subtract(jeV).toString();

                            if (Double.valueOf(newje) < 0 ){
                                String flName = getFlNameById(srid);
                                msgMap.put(msgStr+"-非中央财政收入-["+flName + "]金额不足！", Double.valueOf(entry.getValue().toString()));
                                IsSuccess = false;
                            }
                        }else{
                            String flName = getFlNameById(srid);
                            msgMap.put(msgStr+"-非中央财政收入-["+flName + "]数据不存在！", Double.valueOf(entry.getValue().toString()));
                            IsSuccess = false;
                        }
                    }else{
                        msgMap.put(msgStr+"-非中央财政收入数据不存在！", "tips");
                        IsSuccess = false;
                    }
                }else if (srids.length==2){//项目
                    if (fzyczxmMap.size()>0){
                        String srid = srlx[1].split(":")[0].split("_")[1];// 1,9_:100
                        if (fzyczxmMap.containsKey(srid)){
                            BigDecimal srje = new BigDecimal(fzyczxmMap.get(srid).toString().split(",")[jeIndex]);
                            BigDecimal jeV = new BigDecimal(entry.getValue().toString());
                            String newje = srje.subtract(jeV).toString();

                            if (Double.valueOf(newje) < 0 ){
                                String flid = getFlIdByIdxm(srid);
                                String xmmc = getXmNameByxmId(srid);
                                String flName = getFlNameById(flid);
                                msgMap.put(msgStr+"-非中央财政收入[" +flName +"-"+xmmc+"]金额不足！", Double.valueOf(entry.getValue().toString()));
                                IsSuccess = false;
                            }
                        }else{
                            String flid = getFlIdByIdxm(srid);
                            String flName = getFlNameById(flid);
                            msgMap.put(msgStr+"-非中央财政收入["+flName +"]数据不存在！", Double.valueOf(entry.getValue().toString()));
                            IsSuccess = false;
                        }
                    }else{
                        msgMap.put(msgStr+"-非中央财政收入数据不存在！", "tips");
                        IsSuccess = false;
                    }
                }

            }
        }

        if (IsSuccess)
            msgMap.put("code", "200");
        else
            msgMap.put("code", "300");

        return msgMap;
    }

    /**
     * 中央财政 科目级
     * @return
     */
    public static RecordSet getZycz_KM(int ysnd,int dw){
        RecordSet rs = new RecordSet();
        String sql = " select id,yjsrsy,yqndyjjzsyje,gnkmmc from uf_zyczbksr_km where srnf="+ysnd+" and dw="+dw;
        rs.executeQuery(sql);
        return rs;
    }

    /**
     * 中央财政 下级
     * @return
     */
    public static RecordSet getZycz_XJ(int ysnd,int dw){
        RecordSet rs = new RecordSet();
        String sql = " select id,yjsrsy,yqndyjjzsyje,srzx from uf_zyczbksr_xj where srnf="+ysnd+" and dw="+dw;
        rs.executeQuery(sql);
        return rs;
    }

    /**
     * 根据分类id获取分类名称
     * @param id
     * @return
     */
    public static String getFlNameById(String id){
        RecordSet rs= new RecordSet();
        String sql = " select mc from uf_srysfl where id = "+id+" ";
        rs.executeQuery(sql);
        rs.next();
        return rs.getString("mc");
    }

    /**
     * 根据分类id获取分类名称
     * @param id
     * @return
     */
    public static String getFlIdByIdxm(String id){
        RecordSet rs= new RecordSet();
        String sql = " select fr.szfl from uf_fzysr fr join uf_fzysrxm xm on fr.id = xm.szfl where xm.id = "+id+" ";
        rs.executeQuery(sql);
        rs.next();
        return rs.getString("szfl");
    }

    /**
     * 根据项目id获取项目名称
     * @param id
     * @return
     */
    public static String getXmNameByxmId(String id){
        RecordSet rs= new RecordSet();
        String sql = " select xmmc from uf_fzysrxm where id = "+id+" ";
        rs.executeQuery(sql);
        rs.next();
        return rs.getString("xmmc");
    }

    /**
     * 根据dw及年份筛选非中央组织架构信息
     * @param dw
     * @return
     */
    public static RecordSet getFzycz(Integer dw,Integer ysnd){
        RecordSet rs = new RecordSet();
        String sql = " select szfl flid,yjsrsy,yqndyjjzsyje from uf_fzysr where nf = "+ysnd+" and dw = "+dw+"  ";
        rs.executeQuery(sql);
        return rs;
    }

    /**
     * 根据dw及年份筛选非中央组织架构项目信息
     * @param dw
     * @return
     */
    public static RecordSet getFzyczxm(Integer dw,Integer ysnd){
        RecordSet rs = new RecordSet();
        String sql = " select id xmid,yjsrsy,yqndyjjzsyje from uf_fzysrxm where nf = "+ysnd+" and szdw = "+dw+"  ";
        rs.executeQuery(sql);
        return rs;
    }

    public static RecordSet getDfczbkxm(int nf) {
        RecordSet rs = new RecordSet();
        String sql = " select id,(case nf when " + thisYear + " then yjsrsy else jzsyje end) je,xmmc from uf_dfczbkxm where nf = " + nf + " ";
        rs.executeQuery(sql);
        return rs;
    }

    //非中央
    public static RecordSet getfzyczbkjcsj(int nf, Integer dw) {
        RecordSet rs = new RecordSet();
        String sql = " select srly,(case srnf when " + thisYear + " then yjsrsy else jzje end) je from uf_fzyczbkjcsj where srnf = " + nf + " and srdw = " + dw + " ";
        rs.executeQuery(sql);
        return rs;
    }

    //中央财政 一级
    public static RecordSet getZyczbksr_km(int nf) {
        RecordSet rs = new RecordSet();
        String sql = " select (case srnf when " + thisYear + " then yjsrsy else jzsyje end)srsy,(case srnf when " + thisYear + " then yjsr else snjzje end)srje,id,gnkmmc,yhpje from uf_zyczbksr_km where srnf = " + nf + " ";
        rs.executeQuery(sql);
        return rs;
    }

    //中央财政 下级
    public static RecordSet getZyczbksr_Xj(int nf) {
        RecordSet rs = new RecordSet();
        String sql = " select (case srnf when " + thisYear + " then yjsrsy else jzsyje end)srsy,(case srnf when " + thisYear + " then yjsr else snjzje end)srje,id,srzx,yhpje from uf_zyczbksr_Xj where srnf = " + nf + " ";
        rs.executeQuery(sql);
        return rs;
    }

    //同步一级科目剩余金额
    public static void setSynchronizeKM(String id, Integer ndIndex) {
        RecordSet rs = new RecordSet();
        String sql;
        if (ndIndex == thisYear) { // 0 表示操作本年数据
            sql = " update uf_zyczbksr_km set yjsrsy = yjsr where id in (" + id + ") ";
        } else {
            sql = " update uf_zyczbksr_km set jzsyje = snjzje where id in (" + id + ") ";
        }
        rs.executeUpdate(sql);
    }

    //同步下级科目剩余金额
    public static void setSynchronizeXJ(String id, Integer ndIndex) {
        RecordSet rs = new RecordSet();
        String sql;
        if (ndIndex == thisYear) { // 0 表示操作本年数据
            sql = " update uf_zyczbksr_Xj set yjsrsy = yjsr where id in (" + id + ") ";
        } else {
            sql = " update uf_zyczbksr_Xj set jzsyje = snjzje where id in (" + id + ") ";
        }
        rs.executeUpdate(sql);
    }


    /**
     * 数组转map 并且如果存在相同的key 那么value则相加
     *
     * @param param
     * @return
     */
    public Map<String, Object> arrtoMap(Map<String, Object> param) {//arr:"'1:16,20.00','1:16,11.12','1:2,6.00',...."
        Map<String, Object> map = new HashMap<>();
        for (Map.Entry<String, Object> entry : param.entrySet()) {

        }
//        for (int i = 0; i < arr.length; i++) {
//            String[] split = arr[i].split(":");
//            Integer s1 = Integer.valueOf(split[0]);
//            if(map.get(s1)!=null){
//                map.put(s1,(Double.valueOf(split[1])+ Double.valueOf(map.get(s1).toString())));
//            }else{
//                map.put(s1,split[1]);
//            }
//        }
//        return map;
        return map;
    }

    public static Map<String, Object> getDataBydt(String flowDetailTableNames, String id,String dfxmStr){
        RecordSet rs = new RecordSet();
        Map<String, Object> map = new HashMap<>();
        /*String sql = " select (case when zyczbksr != '' then zyczbksr when CONVERT(varchar(100),dfczbkxm) != '' then dfczbkxm  when zyczbksr != '' then zyczbksr  end) xmid," +
                " hpje,ysly from " + flowDetailTableNames + " where mainid = " + id + " ";
        rs.executeQuery(sql);
        Map<String, Object> map = new HashMap<>();
        while (rs.next()) {
            if (map.containsKey(rs.getString("ysly") + "," + rs.getString("xmid"))) {
                String s = map.get(rs.getString("ysly") + "," + rs.getString("xmid")).toString();
                Double je = Double.valueOf(s);
                map.put(rs.getString("ysly") + "," + rs.getString("xmid"), rs.getDouble("hpje") + je);
            } else {
                map.put(rs.getString("ysly") + "," + rs.getString("xmid"), rs.getDouble("hpje"));
            }
        }*/
        try{
            String sql = " select (case when srlx = 0 then zyczbksr when srlx = 1 then (CAST(zcqd as varchar)+'_'+CAST("+dfxmStr+" as varchar)) end )srid,hpje,srlx from "+flowDetailTableNames+" where mainid = "+id+" ";
            rs.executeQuery(sql);
            while (rs.next()){
                if (map.containsKey(rs.getString("srlx")+","+rs.getString("srid"))){
                    BigDecimal je = new BigDecimal(map.get(rs.getString("srlx")+","+rs.getString("srid")).toString());
                    BigDecimal newje = new BigDecimal(rs.getString("hpje"));
                    map.put(rs.getString("srlx")+","+rs.getString("srid"),je.add(newje));
                }else{
                    map.put(rs.getString("srlx")+","+rs.getString("srid"),rs.getString("hpje"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static String getIdByTable(String flowTableName, String requestId) {
        RecordSet rs = new RecordSet();
        String sql = " select id from " + flowTableName + " where requestId = " + requestId + " ";
        rs.executeQuery(sql);
        rs.next();
        return rs.getString("id");
    }

    /**
     * 根据流程主表id获取流程详细表名称列表
     * @param maindId
     * @return
     */
    public static List<String> getDetailTables(int maindId) {
        List<String> resList = new ArrayList<>();
        RecordSet rs = new RecordSet();
        int formid18 = VersionFlowUtil.getFlowTableLableId(Prop.getPropValue("FormationWorkflowid", "BZ18Workflowid"));
        if(maindId != formid18){
            rs.executeQuery("SELECT d.tablename FROM workflow_billdetailtable d where d.billid=" + maindId + " order by tablename desc;");
            rs.next();
            int i = 0;
            while (i < 2) {
                rs.next();
                resList.add(rs.getString("tablename"));
                i++;
            }
        }else {
            rs.executeQuery("SELECT d.tablename FROM workflow_billdetailtable d where d.billid=" + maindId + " order by tablename desc;");
            int i = 0;
            while (i < 2) {
                rs.next();
                resList.add(rs.getString("tablename"));
                i++;
            }
        }
        return resList;
    }
}
